GDAL/OGR example using shapefile

see http://pcjericks.github.io/py-gdalogr-cookbook/


In [2]:
import os
import ogr

In [3]:
driver_name = 'ESRI Shapefile'
# driver_name = 'FileGDB'
driver = ogr.GetDriverByName(driver_name)
print driver


<osgeo.ogr.Driver; proxy of <Swig Object of type 'OGRDriverShadow *' at 0x106f4f900> >

In [4]:
this_file_directory = os.path.dirname(os.path.realpath('__file__'))
shapefile_path = os.path.join(this_file_directory, 'CA_counties', 'CA_counties.shp')
print os.path.isfile(shapefile_path)


True

In [5]:
ds = driver.Open(shapefile_path)

In [6]:
# dir(ds)

In [7]:
layer = ds.GetLayer(0)
print layer


<osgeo.ogr.Layer; proxy of <Swig Object of type 'OGRLayerShadow *' at 0x106f4fd80> >

In [9]:
print dir(layer)


['AlterFieldDefn', 'Clip', 'CommitTransaction', 'CreateFeature', 'CreateField', 'CreateFields', 'CreateGeomField', 'DeleteFeature', 'DeleteField', 'Dereference', 'Erase', 'FindFieldIndex', 'GetExtent', 'GetFIDColumn', 'GetFeature', 'GetFeatureCount', 'GetFeaturesRead', 'GetGeomType', 'GetGeometryColumn', 'GetLayerDefn', 'GetName', 'GetNextFeature', 'GetRefCount', 'GetSpatialFilter', 'GetSpatialRef', 'GetStyleTable', 'Identity', 'Intersection', 'Reference', 'ReorderField', 'ReorderFields', 'ResetReading', 'RollbackTransaction', 'SetAttributeFilter', 'SetFeature', 'SetIgnoredFields', 'SetNextByIndex', 'SetSpatialFilter', 'SetSpatialFilterRect', 'SetStyleTable', 'StartTransaction', 'SymDifference', 'SyncToDisk', 'TestCapability', 'Union', 'Update', '__bool__', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattr__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__iter__', '__len__', '__module__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__swig_getmethods__', '__swig_setmethods__', '__weakref__', 'next', 'schema', 'this']

In [10]:
layer.GetFeatureCount()


Out[10]:
58

In [49]:
feature = layer.GetFeature(0)
print feature.GetGeometryRef().Simplify(.1).ExportToJson()
dir(feature.GetGeometryRef())


{ "type": "Polygon", "coordinates": [ [ [ -118.360586, 36.744773 ], [ -118.100317, 36.346137 ], [ -118.008043, 35.789161 ], [ -119.538116, 35.789567 ], [ -119.556848, 36.503381 ], [ -118.982441, 36.741646 ], [ -118.360586, 36.744773 ] ] ] }
Out[49]:
['AddGeometry',
 'AddGeometryDirectly',
 'AddPoint',
 'AddPoint_2D',
 'Area',
 'AssignSpatialReference',
 'Boundary',
 'Buffer',
 'Centroid',
 'Clone',
 'CloseRings',
 'Contains',
 'ConvexHull',
 'Crosses',
 'Destroy',
 'Difference',
 'Disjoint',
 'Distance',
 'Empty',
 'Equal',
 'Equals',
 'ExportToGML',
 'ExportToJson',
 'ExportToKML',
 'ExportToWkb',
 'ExportToWkt',
 'FlattenTo2D',
 'GetArea',
 'GetBoundary',
 'GetCoordinateDimension',
 'GetDimension',
 'GetEnvelope',
 'GetEnvelope3D',
 'GetGeometryCount',
 'GetGeometryName',
 'GetGeometryRef',
 'GetGeometryType',
 'GetPoint',
 'GetPointCount',
 'GetPoint_2D',
 'GetPoints',
 'GetSpatialReference',
 'GetX',
 'GetY',
 'GetZ',
 'Intersect',
 'Intersection',
 'Intersects',
 'IsEmpty',
 'IsRing',
 'IsSimple',
 'IsValid',
 'Length',
 'Overlaps',
 'PointOnSurface',
 'Segmentize',
 'SetCoordinateDimension',
 'SetPoint',
 'SetPoint_2D',
 'Simplify',
 'SimplifyPreserveTopology',
 'SymDifference',
 'SymmetricDifference',
 'Touches',
 'Transform',
 'TransformTo',
 'Union',
 'UnionCascaded',
 'Within',
 'WkbSize',
 '__class__',
 '__del__',
 '__delattr__',
 '__dict__',
 '__doc__',
 '__format__',
 '__getattr__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__iter__',
 '__module__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__setstate__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__swig_destroy__',
 '__swig_getmethods__',
 '__swig_setmethods__',
 '__weakref__',
 'next',
 'this']

The unit for Simplify is tolerance, i.e. the maximal distance a vertex can be pleased from its original location.


In [34]:
for feature in layer:
    print feature.name
    # feature.ExportToGeoJson()


Tulare
Calaveras
Merced
San Luis Obispo
Sonoma
Marin
Humboldt
Mono
Del Norte
Colusa
Alameda
El Dorado
Sutter
Kings
Sierra
Lassen
Lake
Tehama
San Francisco
Alpine
Madera
Sacramento
Santa Barbara
Plumas
Modoc
Solano
Ventura
Santa Cruz
Yuba
Tuolumne
Napa
Siskiyou
Placer
Glenn
Trinity
Inyo
San Benito
Monterey
San Diego
Mariposa
Nevada
Mendocino
Yolo
Imperial
Stanislaus
Kern
Contra Costa
Fresno
Santa Clara
San Mateo
Butte
San Joaquin
Amador
Shasta
Riverside
Los Angeles
Orange
San Bernardino

In [ ]: